import { BillCodeGenerator } from './../service/tool.service';
import { Body, Controller, Fields, Files, Inject, Post } from '@midwayjs/core';
import { Animation, AnimationQC } from '../entity/animation.entity';
import { ApiBody, BodyContentType } from '@midwayjs/swagger';
import * as fs from 'fs/promises';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
@Controller('/animation')
export class AnimationController {
  @Inject()
  billCodeGenerator: BillCodeGenerator;
  @InjectEntityModel(Animation)
  repo: Repository<Animation>;
  @Post('/insert')
  @ApiBody({
    contentType: BodyContentType.Multipart,
    type: Animation,
  })
  async insert(
    @Files() uploadCovers: Array<any>,
    @Fields() anmiation: Animation
  ) {
    console.log(uploadCovers);
    console.log('xxx');
    console.log(anmiation);
    const id = await this.billCodeGenerator.nextCode('AN');
    anmiation.aniCode = id;
    if (uploadCovers.length > 0) {
      console.log('上传的封面文件 旧名字是: ' + uploadCovers[0].filename);
      console.log('上传的封面文件 新名字是: ' + id + '.jpg');
      anmiation.cover = '/' + id + '.jpg';
      // 转移图片等多媒体文件
      await fs.copyFile(
        uploadCovers[0].data,
        '/home/xieweig/main/photo' + '/animation' + anmiation.cover
      );
    }
    // 数据库存储记录
    console.log('待存储的', anmiation);
    return await this.repo.save(anmiation);
  }
  /* 

select * from Anmiation a 
where a.title like '%titleLike%'
order by a.aniCode desc
limit 0,3
*/
  @Post('/query')
  async query(@Body() animationQC: AnimationQC) {
    const { pageNum, pageSize, titleLike } = animationQC;
    const pageStart = (pageNum - 1) * pageSize;
    const builder = this.repo.createQueryBuilder('a');
    if (titleLike) {
      builder.andWhere(' a.title like :titleLike', {
        titleLike: '%' + titleLike + '%',
      });
    }
    builder.orderBy('a.aniCode', 'DESC');
    builder.offset(pageStart).limit(pageSize);
    const r = await builder.printSql().getManyAndCount();
    return {
      results: r[0],
      total: r[1],
      prefix:'animation'
    };
  }
}
